<?php
include_once 'ns_dao.class.php';


class ns_dao_user
{

    // -----------------------------------------------------------------------------------------------------------------------------------
    //  USER
    // -----------------------------------------------------------------------------------------------------------------------------------
    
    public static function CreateNewUser($username, $password, $firstName, $lastName, $email, $phone)
    {
        $DB = ns_dao::create();
        $sql = "INSERT INTO user (Username, Password, FirstName, LastName, Email, Phone, UserLevel) VALUES ('{$username}','{$password}','{$firstName}','{$lastName}','{$email}','{$phone}',1)";
        $sql_result = $DB->DB->insert($sql);
        unset($DB);
        return $sql_result;
    }

    public static function DeleteUser($username)
    {
        $DB = ns_dao::create();
        $sql = "DELETE FROM user WHERE Username='{$username}'";
        $sql_result = $DB->query($sql);
        unset($DB);
        return $sql_result;
    }
    
    public static function updateUser($username, $field, $value)
    {
        $DB = ns_dao::create();
        $rowCount = $DB->update("UPDATE user SET {$field} = '{$value}' WHERE Username = '{$username}'");
        unset($DB);
        return ($rowCount >= 1) ? TRUE : FALSE;
    }

    public static function updateUserByArray($username, $data)
    {
        //Modified since last revision to suit username as PK
        $insertData = array();
        foreach ($data as $key => $value)
            if ($key != "Username")
                $insertData[$key] = (is_null($value)) ? '' : $value;

        foreach ($insertData as $key => $value)
            if (!is_numeric($value) || $key == "Phone")
                $insertData[$key] = "'{$value}'";

        $sql   = "UPDATE user SET ";
        $blnFirst = true;
        foreach ($insertData as $key => $value){
            if ($blnFirst){
                $blnFirst = false;
                $sql = $sql . $key . "=" . $value;
            } else {
                $sql = $sql . "," . $key . " = " . $value;
            }
        }
        $sql .= " WHERE Username='" . $username . "'";
        $DB = ns_dao::create();
        $rowCount = $DB->update($sql);
        unset($DB);

        return ($rowCount >= 1) ? TRUE : FALSE;
    }

    public static function  UserByUsername($username)
    {
        logger::called();
        $DB = ns_dao::create();
        if (is_null($DB)) return null;
        $sql_result = $DB->query("SELECT * FROM user WHERE Username = '{$username}' LIMIT 1");
        if (is_null($sql_result)) return null;
        if (count($sql_result) <= 0 ) return null;
        $U = User::createFromArray($sql_result[0]);
        unset($DB);
        return $U;
    }

    public static function GetUsersList()
    {
        $DB = ns_dao::create();
        $sql_result = $DB->query("SELECT * FROM user");

        foreach ($sql_result as $key => $user_row)
            $result[$key] = User::createFromArray($user_row);

        unset($DB);
        return $result;
    }

    public static function GetUserLevelList()
    {
        $DB = ns_dao::create();
        $sql_result = $DB->query("SELECT * FROM userlevel");
        foreach ($sql_result as $key => $userLevel_row)
            $result[$key] = UserLevel::createFromArray($userLevel_row);

        unset($DB);
        return $result;
    }

    public static function UpdateUsersLastSeenMessage($username)
    {
        $DB = ns_dao::create();
        $sql = "SELECT MAX(MessageID) FROM message";
        $sql_result = $DB->query($sql);
        $maxID = $sql_result[0]["MAX(MessageID)"];
        $success = ns_dao_user::updateUser($username, "LastSeenMessageID", $maxID);
        unset($DB);
        return $success;
    }

    public static $AUTH_OK = "AuthOK";
    public static $AUTH_FAIL = "AuthFail";
    public static function authenticateUser($username, $password)
    {
        $DB = ns_dao::create();
        $sql_result = $DB->query("SELECT * FROM user WHERE Username = '{$username}' AND Password = '{$password}' LIMIT 1");
        $result = count($sql_result);
        unset($DB);
        return ($result >= 1) ? self::$AUTH_OK : self::$AUTH_FAIL;
    }

    public static function CreateLoginKey($username)
    {
        $loginKey = 0;
        $result = 0;

        $DB = ns_dao::create();
        do {
            $loginKey = mt_rand();
            $sql_result = $DB->query("SELECT * from login WHERE loginKey = '{$loginKey}'");
            $result = count($sql_result);
        } while ($result != 0);
       

        $birthTime = gmdate("Y-m-d H:i:s", time());
        $deathTime = gmdate("Y-m-d H:i:s", time() + 600); //Time plus 10 mins
        $sql_result = $DB->query("INSERT INTO login (LoginKey, Username, BirthTime, DeathTime) VALUES ('{$loginKey}','{$username}','{$birthTime}','{$deathTime}')");

        unset($DB);
        return $loginKey;
    }

    public static function CheckLoginKey($loginKey)
    {
        $DB = ns_dao::create();
        $sql_result = $DB->query("SELECT TIME_TO_SEC(TIMEDIFF(DeathTime, UTC_TIMESTAMP())) AS TimeTillDeath FROM login WHERE LoginKey = '$loginKey'");
        if ($sql_result == false ){
            return self::$AUTH_FAIL;
        }

        $result = count($sql_result);
        unset($DB);

        if ($result <= 0)
        {
            return self::$AUTH_FAIL;
        }

        $timeTillDeath  = $sql_result[0]["TimeTillDeath"];
        if ($timeTillDeath > 0)
        {
            return self::$AUTH_OK;
        }
        return self::$AUTH_FAIL;

    }

    public static function GetUsernameFromLoginKey($loginKey)
    {
        $DB = ns_dao::create();
        $sql_result = $DB->query("SELECT Username FROM login WHERE LoginKey = '{$loginKey}' LIMIT 1");
        unset($DB);
        return $sql_result[0]["Username"];
    }

    public static function PreserveLoginKey($loginKey)
    {
        $deathTime = gmdate("Y-m-d H:i:s", time() + 600);
        $DB = ns_dao::create();
        $rowCount = $DB->update("UPDATE login SET DeathTime = '{$deathTime}' WHERE LoginKey = '{$loginKey}'");
        unset($DB);
        return ($rowCount >= 1) ? TRUE : FALSE;
    }

    public static function KillLoginKey($loginKey)
    {
        $deathTime = gmdate("Y-m-d H:i:s", time());
        $DB = ns_dao::create();
        $rowCount = $DB->update("UPDATE login SET DeathTime = '{$deathTime}' WHERE LoginKey = '{$loginKey}'");
        unset($DB);
        return ($rowCount >= 1) ? TRUE : FALSE;
    }





//
//    public static function Users()
//    {
//        $DB = ns_dao::create();
//        $sql_result = $DB->query("SELECT * FROM User",'Username');
//
//        foreach ($sql_result as $key => $user_row)
//            $result[$key] = User::createFromArray($user_row);
//
//        unset($DB);
//
//        return $result;
//
//    }

}
?>
